package ar.edu.uba.fi.jmit.monitorengine.backend.client.view;

import java.util.LinkedList;
import java.util.List;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class ConfirmationDialog extends DialogBox {
	
	private Label messageLabel;
	
	private Button buttonYes;
	
	private Button buttonNo;
	
	private List<ConfirmDialogHandler> listeners;
	
	public ConfirmationDialog(String message) {
		this("Confirm", message);
	}
	
	public ConfirmationDialog(String title, String message) {
		super(false, true);
		listeners = new LinkedList<ConfirmDialogHandler>();
		this.setTitle(title);
		this.setText(title);
		this.setSize("400", "150");
		messageLabel = new Label();
		messageLabel.setText(message);
		setAnimationEnabled(true);
		this.center();
		this.add(this.createConfirmationPanel());
		this.addListeners();
	}

	private Widget createConfirmationPanel() {
		Panel panel = new VerticalPanel();
		panel.setSize("100%", "100%");
		panel.add(messageLabel);
		panel.add(createButtonsPanel());
		return panel;
	}

	private Widget createButtonsPanel() {
		Panel panel = new HorizontalPanel();
		buttonYes = new Button("Yes");
		panel.add(buttonYes);
		panel.add(new HTML("&nbsp;"));
		buttonNo = new Button("No");
		panel.add(buttonNo);
		return panel;
	}
	
	public void addConfirmHandler(ConfirmDialogHandler listener) {
		listeners.add(listener);
	}
	
	private void addListeners() {
		buttonYes.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent arg0) {
				notifyConfirm();
				hide();
			}

		});
		
		buttonNo.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent arg0) {
				notifyCancel();
				hide();
			}

		});
		
	}
	
	private void notifyConfirm() {
		for(ConfirmDialogHandler listener:listeners) {
			listener.onConfirm();
		}
	}
	
	private void notifyCancel() {
		for(ConfirmDialogHandler listener:listeners) {
			listener.onCancel();
		}
	}

}
